/*
    $Id$
    MAR another horizontal scroll action game
    Copyright (C) 2009 Japan Manoretimedia Lab.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "script.h"
#include <tolua++.h>
#include <lua.hpp>
#include "glue/main_glue.h"
#include <assert.h>
#include "util.h"

struct Script {
    lua_State *L;
};

Script *Script_Instance(void)
{
    static Script self;

    return &self;
}

void
Script_Init(Script *self)
{
    assert(self);

    self->L = lua_open();
    luaL_openlibs(self->L);
    tolua_main_open(self->L);
}

void
Script_Term(Script *self)
{
    assert(self);

    lua_close(self->L);
}

void
Script_Load(Script *self, const char *scriptFileName)
{
    assert(self);

    int top = lua_gettop(self->L);
    int ret = luaL_dofile(self->L, scriptFileName);
    lua_settop(self->L, top);
    if (ret != 0) {
        DebugMessageBox(L"error: %S\n", lua_tostring(self->L, -1));
        return;
    }
}

int
Script_PCall(Script *self, const char *fname)
{
    assert(self);

    lua_getglobal(self->L, fname);
    int ret = lua_pcall(self->L, 0, 0, NULL);
    if (ret) {
        DebugMessageBox(L"error: %S %S\n", fname, lua_tostring(self->L, -1));
        lua_pop(self->L, 1);
    }
    return ret;
}
